// pages/balance/index.js
const api = require('../../utils/api.js')
const app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        amount: '',
        items: [100, 500, 1000, 1500, 3000],
        checkValue: '',
        userId: '',
        balance: '',
        totalBalance:'',
        rewardsBalance:'',
        isYLPay: false,
        list:[],
        total:''
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        console.log(options)
        var that = this
        api.post('shop/getPayChannel',{
            shopId: app.globalData.shopId
          }).then( res=>{
            if(res.data.data === 1){
              that.setData({
                isYLPay: true
              })
            }     
          })
        this.setData({
          userId: options.userId,
        })
        this.getActivity()
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        var that = this
        // wx.showLoading({
        //   title: '加载中',
        // })
        setTimeout(function () {
            api.post('user/getByMobile', {
                mobile: wx.getStorageSync('phone'),
                openid: wx.getStorageSync('user').openid,
                shopId: app.globalData.shopId,
            }).then(res => {
                console.log(res)
                // 获取用户信息
                if (res.data.success) {
                    that.setData({
                        balance: res.data.data.balance / 100 || 0,
                        rewardsBalance:res.data.data.rewardsBalance / 100 || 0,
                        totalBalance:res.data.data.totalBalance / 100 || 0
                    })

                    wx.hideLoading()
                }

            })
        }, 200)

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    },
    /* 点击按钮填充金额 */
    setAmount: function (e) {
        if (e.currentTarget.dataset.value) {
            this.setData({
                amount: e.currentTarget.dataset.value
                // checkValue: e.currentTarget.dataset.value
            });
        }
    },
    /* 跳转【充值记录】 */
    goRechargeRecording: function () {
        wx.navigateTo({
            url: '/pages/rechargeRecorde/index?userId=' + this.data.userId
        })
    },
    /* 点击充值 */
    handelRecharge: function (event) {
        if(this.data.isYLPay){
            api.post('funds/user/account/deposit', {
                amount: parseInt((this.data.amount * 100).toFixed(0)),
                userId: this.data.userId + '',
                openId: wx.getStorageSync('user').openid + '',
                shopId: app.globalData.shopId + ''
            }).then(res => {
                if (res.data.success) {
                    wx.requestPayment({
                        timeStamp: res.data.data.timeStamp + '',
                        nonceStr: res.data.data.nonceStr + '',
                        package: res.data.data.package + '',
                        signType: res.data.data.signType + '',
                        paySign: res.data.data.paySign + '',
                        success: function (res) {
                            console.log(res)
                            setTimeout(function () {
                                wx.reLaunch({
                                    url: '/pages/user/index'
                                  })
                              }, 200)
                        },
                        fail: function (res) {
                            console.log(res)
                        }
                    })
                }else{
                     wx.showToast({
                        title: res.data.message,
                        icon: 'none',
                        duration: 1500
                      })
                }
            });
        }else{
            api.post('funds/user/account/wechatdeposit', {
                amount: parseInt((this.data.amount * 100).toFixed(0)),
                userId: this.data.userId + '',
                openId: wx.getStorageSync('user').openid + '',
                shopId: app.globalData.shopId + ''
            }).then(res => {
                if (res.data.success) {
                    wx.requestPayment({
                        timeStamp: res.data.data.timeStamp + '',
                        nonceStr: res.data.data.nonceStr + '',
                        package: res.data.data.package + '',
                        signType: res.data.data.signType + '',
                        paySign: res.data.data.paySign + '',
                        success: function (res) {
                            console.log(res)
                            setTimeout(function () {
                                wx.reLaunch({
                                    url: '/pages/user/index'
                                  })
                              }, 200)
                        },
                        fail: function (res) {
                            console.log(res)
                        }
                    })
                }else{
                    wx.showToast({
                        title: res.data.message,
                        icon: 'none',
                        duration: 1500
                      })
                }
            });
        }
      
        let formId = event.detail.formId;
        // 忽略开发者工具里边的formId
        if (formId && formId !== 'the formId is a mock one') {
            this.saveFormId(formId)
            console.log('formId:' + formId)
        }
    },
    /* 失去焦点 获取金额 */
    getAmount: function (e) {
        this.setData({
            amount: e.detail.value,
        })
    },
    /* 点击校验 */
    handelCheck: function (e) {
        e.detail.value = e.detail.value.replace(/\-/g, "")
        e.detail.value = e.detail.value.replace(/\.{2,}/g, ".")
        e.detail.value = e.detail.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".")
        e.detail.value = e.detail.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); //只能输入两个小数
        if (e.detail.value.indexOf('.') == 0) {//第一位就是 .
            e.detail.value = '0' + e.detail.value
        }

        this.setData({
            amount: e.detail.value,
        })
    },
    /* 保存formid */
    saveFormId: function (id) {
        api.post('user/saveFormid',{
          openid: wx.getStorageSync('user').openid,
          shopId: app.globalData.shopId,
          formid: id
        }).then(res =>{
          console.log(res)
        })
      },
      /* 获取运营活动 */
      getActivity: function() {
          var that = this;
          api.post('/operation/activity/getActivty',{
            activityTypeId: 1,
            page:1,
            pageSize: 3,
            shopId: app.globalData.shopId,
            status: 1
          }).then(res=>{
              let arr =[]
              res.data.data.list.map(item=>{
                arr.push( {
                    thresholdStart: item.thresholdStart/100,
                    activityName:item.activityName
                })
                that.setData({
                    list: arr,
                    total: res.data.data.total
                })

              })
          })
      }
})
